package com.yljk.yljkproject.manager;

import android.media.MediaRecorder;

import com.hyphenate.chat.EMClient;
import com.hyphenate.util.PathUtil;
import com.yilijk.base.utils.ALog;
import com.yljk.yljkproject.utils.ReactUtils;

import java.io.File;
import java.io.IOException;
/**
 * Create By shicheng
 *
 * 录音管理
 * Android mediaplayer recorder <amr to mp3> manager
 *
 */
public class MediaRecorderManager {
    private final String PREFIX = "/VoiceMessage";
    private final String EXTENSION = ".amr";
    static String voiceFileName = null;
    static String voiceFilePath = null;
    private File soundFile = null;
    static MediaRecorder mediaRecorder = null;
    static MediaRecorder recorder;
    static File file;
    static long starttime;
    static long endtime;



    public static void MediaRecorderStart(){
        file = null;
        try {
            if (recorder != null) {
                recorder.release();
                recorder = null;
            }
            recorder = new MediaRecorder();
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            voiceFileName = ReactUtils.INSTANCE.getVoiceFileName(EMClient.getInstance().getCurrentUser());
            voiceFilePath = PathUtil.getInstance().getVoicePath() + "/" + voiceFileName;
            file = new File(voiceFilePath);
            recorder.setOutputFile(file.getAbsolutePath());
            recorder.prepare();
            recorder.start();
            starttime = System.currentTimeMillis();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void MediaRecorderStop(){
        try {
            recorder.stop();
            endtime = System.currentTimeMillis();
            recorder.release();
            recorder = null;
        } catch (RuntimeException e) {
            recorder.reset();
            recorder.release();
            recorder = null;
        }
    }
    public static String getMediaRecorderPath(){
        File isFile = new File(voiceFilePath);
        if (isFile.exists()){
            return isFile.getAbsolutePath();
        }else{
            ALog.d("文件不存在", "getMediaRecorderPath: ");
            return "";
        }
    }
    /**
     * Android 音乐播放器应用里，读出的音乐时长为 long 类型以毫秒数为单位，例如：将 234736 转化为分钟和秒应为 03:55 （包含四舍五入）
     */
    public static int getMediaRecorderTime(){
        //计算当前的语音时长
        long l = endtime - starttime;
        ALog.d("long time", "getMediaRecorderTime: "+l);
        int seconds = (int) (l / 1000);
        return seconds;



    }


}

